'''
Created on 2013-3-15

@author: gavin
'''

from subprocess import call
import argparse
import logging
import os
from functools import partial

            
def commandAssemble(script_cmd, base_dir, file_name=''):
    filePath = os.path.join(base_dir, file_name)
    if os.path.exists(filePath):
        return script_cmd + filePath
    else:
        return None
    

def execScript(script_cmd, base_dir, func_filter, recursivedDepth):
    
    filtered_cmd = func_filter(script_cmd, base_dir)
    
    if filtered_cmd:
        logging.info(str(filtered_cmd))
        call(filtered_cmd)
    
    if recursivedDepth > 0 and os.path.isdir(base_dir):
        recursivedDepth -= 1
        for eachSubDir in os.listdir(base_dir):
            execScript(script_cmd, os.path.join(base_dir, eachSubDir), func_filter, recursivedDepth)
        

if __name__ == '__main__':
#log setting
    logging.getLogger().setLevel(logging.INFO)
    parser = argparse.ArgumentParser(description='This is a script application')
    parser.add_argument('-f', '--sourcefile', help='file',default='.')
    parser.add_argument('-c','--cmd', default= 'cmd.exe /c mvn deploy -f ')
    parser.add_argument('-d','--description', default='pom.xml')
    
        
    # basePath is the absolute path of ../.. relative to this script location
    basePath = reduce (lambda l,r: l + os.path.sep + r, os.path.dirname( os.path.realpath( __file__ ) ).split( os.path.sep )[:-2] )
    
    
    
    args = parser.parse_args()
    inputFiles = ''
    if(args.sourcefile == '.'):
        inputFiles = basePath
    else:
        inputFiles = args.sourcefile
    
#    invokeCMD(args.cmd, inputFiles, args.description)
    
    execScript(args.cmd, inputFiles, partial(commandAssemble, file_name=args.description) , 1)
        
